const defaultDbPath = '_doc/cable/cable.db'

export function openDatabase(path = defaultDbPath) {
  return new Promise((resolve, reject) => {
    plus.sqlite.openDatabase({
      name: 'main',
      path: path,
      success: () => {
        console.log('[sqlite] opened')
        resolve('ok.')
      },
      fail: (error) => {
        reject(error)
      },
    })
  })
}

export function isOpenDatabase(path = defaultDbPath) {
  return plus.sqlite.isOpenDatabase({
    name: 'main',
    path: path,
  })
}

export function selectSql(sql) {
  return new Promise((resolve, reject) => {
    if (!isOpenDatabase()) {
      openDatabase().then(() => {
        plus.sqlite.selectSql({
          name: 'main',
          sql: sql,
          success: (data) => {
            resolve(data)
          },
          fail: (error) => {
            reject(error)
          },
        })
      })
    } else {
      plus.sqlite.selectSql({
        name: 'main',
        sql: sql,
        success: (data) => {
          resolve(data)
        },
        fail: (error) => {
          reject(error)
        },
      })
    }
  })
}

export function closeDatabase(path = defaultDbPath) {
  return new Promise((resolve, reject) => {
    plus.sqlite.closeDatabase({
      name: 'main',
      path: path,
      success: function (e) {
        resolve()
        console.log('closeDatabase success!')
      },
      fail: function (e) {
        reject()
        console.log('closeDatabase failed: ' + JSON.stringify(e))
      },
    })
  })
}
